package com.wechat.wechat.service.impl;

import com.sun.xml.internal.bind.v2.TODO;
import com.wechat.wechat.converter.OrderMaster2OrderDTOConverter;
import com.wechat.wechat.dto.CartDTO;
import com.wechat.wechat.dto.OrderDTO;
import com.wechat.wechat.entity.OrderDetail;
import com.wechat.wechat.entity.OrderMaster;
import com.wechat.wechat.entity.ProductInfo;
import com.wechat.wechat.enums.OrderStatusEnum;
import com.wechat.wechat.enums.PayStatusEnum;
import com.wechat.wechat.enums.ResultEnum;
import com.wechat.wechat.exception.SellException;
import com.wechat.wechat.repository.OrderDetailRepository;
import com.wechat.wechat.repository.OrderMasterRepository;
import com.wechat.wechat.repository.ProductInfoRepository;
import com.wechat.wechat.service.OrderService;
import com.wechat.wechat.service.PayService;
import com.wechat.wechat.service.ProductService;
import com.wechat.wechat.service.PushMessageService;
import com.wechat.wechat.utils.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.persistence.Entity;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author NN
 * @2020/2/20 16:02
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private ProductService productService;
    @Autowired
    private PayService payService;
    @Autowired
    private PushMessageService pushMessageService;
    @Autowired
    private WebSocket webSocket;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId=KeyUtil.getUniqueKey();
        BigDecimal orderAmount=new BigDecimal(0);
        //1.遍历订单详情列表，查询对应的商品
        for(OrderDetail orderDetail: orderDTO.getOrderDetailList()) {
            //根据商品id查询商品信息
            ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            // 增加订单详情记录
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetail.setDetailId(KeyUtil.getUniqueKey());
            orderDetail.setOrderId(orderId);
            orderDetailRepository.save(orderDetail);
            //计算订单总价
            orderAmount = orderDetail.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);
        }
        //2.增加订单记录
        OrderMaster orderMaster=new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMasterRepository.save(orderMaster);

        //3.扣库存
        //将购买商品id和数量放到购物车列表中
        List<CartDTO> cartDTOList=orderDTO.getOrderDetailList().stream().map(e->
                new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.decreaseStock(cartDTOList);
        orderDTO.setOrderId(orderId);
        //向卖家端发送webscoket消息
        webSocket.sendMessage(orderDTO.getOrderId());
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        //查询订单主表
        OrderMaster orderMaster=orderMasterRepository.findOne(orderId);
        if(orderMaster==null)
        {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //查询订单详情
        List<OrderDetail> orderDetailList=orderDetailRepository.findByOrderId(orderId);
        if(orderDetailList.isEmpty())
        {
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO=new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String openId, Pageable pageable) {
        Page<OrderMaster> orderMasterList= orderMasterRepository.findByBuyerOpenid(openId,pageable);
        List<OrderDTO> orderDTOList= OrderMaster2OrderDTOConverter.convert(orderMasterList.getContent());

        return new PageImpl(orderDTOList,pageable,orderMasterList.getTotalElements());
    }

    /*取消订单*/
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {

        OrderMaster orderMaster=new OrderMaster();
        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode()))
        {
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //更新订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster result=orderMasterRepository.save(orderMaster);
        if(result==null)
        {
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        //回滚库存
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList()))
        {
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList=orderDTO.getOrderDetailList().stream().map(
                e->new CartDTO(e.getProductId(),e.getProductQuantity())
        ).collect(Collectors.toList());
        productService.increaseStock(cartDTOList);
        //退款
        if(orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS))
        {
            payService.refund(orderDTO);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        OrderMaster orderMaster=new OrderMaster();
        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode()))
        {
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //更新订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster result=orderMasterRepository.save(orderMaster);
        if(result==null)
        {
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        //推送订单完结消息
        pushMessageService.orderStatus(orderDTO);
        return orderDTO;

    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        OrderMaster orderMaster=new OrderMaster();
        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode()))
        {
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //判断订单支付状态
        if(!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode()))
        {
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
        //更新订单状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster result=orderMasterRepository.save(orderMaster);
        if(result==null)
        {
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> orderMasterList= orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList= OrderMaster2OrderDTOConverter.convert(orderMasterList.getContent());
        return new PageImpl(orderDTOList,pageable,orderMasterList.getTotalElements());
    }
}
